<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
            <el-form-item label="创建时间" style="width: 308px">
                <el-date-picker
                    v-model="dateRange"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5" style="display: flex; justify-content: center;">
                <h3 class="business-analysis-title">商机分析</h3>
            </el-col>
        </el-row>

        <div id="business-chart" style="width: 100%; height: 400px; margin-bottom: 20px;"></div>

        <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="time" label="时间" width="180" />
            <el-table-column prop="increment" label="商机增量" width="180" />
            <el-table-column prop="stock" label="商机存量" />
            <template #empty>
                <div class="empty-data">
                    暂无数据
                </div>
            </template>
        </el-table>


    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { getBusinessAnalysis } from '@/api/tienchin/business';

const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
});
const dateRange = ref([]);
const showSearch = ref(true);
const tableData = ref([]);

// Echarts图表相关
let businessChart = null;

onMounted(() => {
    initChart();
    handleQuery(); // 页面加载时立即请求数据
});

function initChart(increaseData = [], totalData = [], timeData = []) {
    if (businessChart != null && businessChart.dispose) {
        businessChart.dispose();
    }
    businessChart = echarts.init(document.getElementById('business-chart'));
    const option = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['增量数据', '存量数据'],
            bottom: 0,
            itemGap: 30,
            padding: [5, 0, 0, 0]
        },
        xAxis: {
            type: 'category',
            data: timeData // 动态设置时间数据
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '增量数据',
                type: 'line',
                data: increaseData // 动态设置增量数据
            },
            {
                name: '存量数据',
                type: 'line',
                data: totalData // 动态设置存量数据
            }
        ]
    };
    businessChart.setOption(option);
}

async function handleQuery() {
    // 处理搜索逻辑
    console.log('搜索', queryParams.value, dateRange.value);

    try {
        // 将日期范围添加到查询参数中，格式化为 'YYYY-MM-DD 12:00:00'
        if (dateRange.value && dateRange.value.length === 2) {
            const start = dateRange.value[0].slice(0, 10) + ' 12:00:00';
            const end = dateRange.value[1].slice(0, 10) + ' 12:00:00';
            queryParams.value['dateRange[0]'] = start;
            queryParams.value['dateRange[1]'] = end;
            queryParams.value['params[beginTime]'] = start;
            queryParams.value['params[endTime]'] = end;
        } else {
            queryParams.value['dateRange[0]'] = undefined;
            queryParams.value['dateRange[1]'] = undefined;
            queryParams.value['params[beginTime]'] = undefined;
            queryParams.value['params[endTime]'] = undefined;
        }

        // 移除分页参数，确保请求全部数据
        delete queryParams.value.pageNum;
        delete queryParams.value.pageSize;

        const res = await getBusinessAnalysis(queryParams.value);
        if (res.code === 200 && res.data) {
            const { increase, total } = res.data;

            // 处理图表数据
            const allTimes = new Set();
            increase.forEach(item => allTimes.add(item.time));
            total.forEach(item => allTimes.add(item.time));

            const timeData = Array.from(allTimes).sort();
            const increaseChartData = [];
            const totalChartData = [];
            tableData.value = [];

            timeData.forEach(time => {
                const inc = increase.find(item => item.time === time)?.value || 0;
                const tot = total.find(item => item.time === time)?.value || 0;
                increaseChartData.push(inc);
                totalChartData.push(tot);
                tableData.value.push({
                    time: time,
                    increment: inc,
                    stock: tot
                });
            });

            initChart(increaseChartData, totalChartData, timeData);
        } else {
            console.error('获取商机分析数据失败或数据格式不正确:', res);
            // 清空图表和表格数据
            initChart([], [], []);
            tableData.value = [];
        }
    } catch (error) {
        console.error('请求商机分析数据出错:', error);
        // 清空图表和表格数据
        initChart([], [], []);
        tableData.value = [];
    }
}

function resetQuery() {
    dateRange.value = [];
    queryParams.value = {
        pageNum: 1,
        pageSize: 10,
    };
    handleQuery();
}
</script>

<style lang="scss" scoped>
.business-analysis-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
}

.empty-data {
    text-align: center;
    padding: 20px;
    color: #909399;
}

.legend-container {
    margin-top: 20px;
    text-align: center;
}

.legend-item {
    margin-right: 20px;
    display: inline-flex;
    align-items: center;
    font-size: 14px;
    color: #606266;
}

.legend-dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-right: 5px;
}

.legend-dot.increment {
    background-color: #E6A23C; /* 黄色 */
}

.legend-dot.stock {
    background-color: #409EFF; /* 蓝色 */
}
</style>